﻿using System;
using System.Reflection;
using System.Linq.Expressions;
using System.Linq;
using System.Runtime.Serialization;

namespace ExpressionSerialization
{

  [DataContract]
  public class XConstantExpression : XExpression
  {
    [DataMember]
    public object Value { get; set; }

    public override void FromExpression(Expression source_)
    {
      base.FromExpression(source_);
      var exp = source_ as ConstantExpression;
      //todo: zjisti, jestli je serializable
      //todo: změnit typ
      Type valueType = exp.Value.GetType();
      if(valueType.IsValueType || valueType==typeof(string)) {
        //if(valueType.IsSerializable) {
          Value = exp.Value;
        //} else {
        //  throw new Exception("I have problem");
        //}
      } else if(valueType.IsClass){
        // First field contains value
        var xx = valueType.GetFields();
        if(xx.Length >= 1) {
          if(!valueType.IsPublic) {
            throw new Exception("Local variables are not supported -" + xx[0].Name);
          }
          Value = xx[0].GetValue(exp.Value);
          TypeName = Value.GetType().ToSerializableForm();
        }
      }
    }

    public override Expression ToExpression(Type dataContract_, System.Collections.Generic.List<ParameterExpression> parameters_)
    {
      return Expression.Constant(Value);
    }
    

  }
}
